<?php
class PublicSurveyOption extends Module  
{
	function PublicSurveyOption($row)
	{
		Module::Module($row);
		
		CGlobal::$website_title = AZNet::$page['title'];
		
		if(User::is_admin())
		{
			$this->add_form(new PublicSurveyOptionForm());
		}
		else 
		{
			Url::access_denied();
		}
	}
}

class PublicSurveyOptionForm extends Form
{
	var $public_survey = false;
	
	function PublicSurveyOptionForm()
	{
		Form::Form('PublicSurveyOptionForm');
		
		if (Url::get('cmd') == 'delete' && Url::get('id',0))
		{
			DB::query('DELETE FROM public_survey_opinion WHERE id='.Url::get('id',0));
			
			Url::redirect_current(array('id_survey'));
		}
		
		$id_survey	= (int)Url::get('id_survey',0);
		
		if($id_survey)
		{
			$this->public_survey = DB::select('public_survey', "id=$id_survey");
			
			if (!$this->public_survey)
			Url::redirect_current();
		}
	}
	
	function on_submit()
	{
		$txt_option = 	Url::get('txt_option','');
		$id			=	Url::get('id',0);
		
		if($txt_option != '')
		{
			if ($id==0)
				DB::insert('public_survey_opinion',array('id_survey'=>$this->public_survey['id'],'option'=>$txt_option));
			else
				DB::update('public_survey_opinion',array('option'=>$txt_option),'id='.$id);
		}
		
		Url::redirect_current(array('id_survey'));
	}
	
	function draw()
	{
		global $display;
		
		$cmd	=	Url::get('cmd');

		$display->add('id_survey',			$this->public_survey['id']);
		$display->add('title',				stripslashes($this->public_survey['title']));
		$display->add('question',			stripslashes($this->public_survey['question']));
		
		$display->add('url_edit',Url::build('admin_survey',array('cmd'=>'edit','id_survey'=>$this->public_survey['id'])));

		$opts = DB::fetch_all('SELECT * FROM `public_survey_opinion` WHERE `id_survey`='.$this->public_survey['id']);
		$i = 0;
		
		foreach($opts as &$opt)
		{
			$i++;
			
			$opt['num'] 	= $i;
			$opt['edit'] 	=  Url::build_current(array('id_survey'=>Url::get('id_survey','int',0),'cmd'=>'edit','id'=>$opt['id']));
			$opt['del'] 	=  Url::build_current(array('id_survey'=>Url::get('id_survey','int',0),'cmd'=>'delete','id'=>$opt['id']));
		}
		
		$display->add('opts',$opts);
		
		if ($cmd=='edit')
		{
			$public_survey_opinion	=	DB::select('public_survey_opinion','id='.Url::get('id',0));
			
			if($public_survey_opinion)
			{
				$display->add('value',	$public_survey_opinion['option']);
				$display->add('option_id',	$public_survey_opinion['id']);
			}
		}
		
		$this->beginForm();
		$display->output('PublicSurveyOption');
		$this->endForm();
	}
}
?>